package github.nisrulz.projecteasydeviceinfo;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

import github.nisrulz.projecteasydeviceinfo.slice.SplashAbilitySlice;

public class SplashAbility extends Ability {
    private boolean launched = false;
    private static final String[] requestBasicPermissions =
        {
            SystemPermission.LOCATION,
            SystemPermission.LOCATION_IN_BACKGROUND
        };

    private static void setFullScreen(Ability ability) {
        ability.getWindow()
            .addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setFullScreen(this);
        super.setMainRoute(SplashAbilitySlice.class.getName());
        boolean hasFineLocation =
            RuntimePermissionUtil.checkPermissionGranted(this, SystemPermission.LOCATION);
        if (hasFineLocation) {
            loadMainActivity();
        } else {
            RuntimePermissionUtil.requestPermission(this, requestBasicPermissions, 100);
        }
    }

    private void loadMainActivity() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withBundleName("github.nisrulz.projecteasydeviceinfo")
            .withAbilityName("github.nisrulz.projecteasydeviceinfo.MainAbility")
            .build();
        intent.setOperation(operation);
        startAbility(intent, 10);
        launched = true;
        terminateAbility();
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 100) {
            RuntimePermissionUtil.onRequestPermissionsResult(grantResults, new RPResultListener() {
                @Override
                public void onPermissionGranted() {
                    if (grantResults[0] == IBundleManager.PERMISSION_GRANTED
                        && !launched) {
                        loadMainActivity();
                    }
                }

                @Override
                public void onPermissionDenied() {
                    // do nothing
                }
            });
        }
        return;
    }
}
